/*
 * Keith.cpp
 *
 *  Created on: Dec 7, 2012
 *      Author: Todd
 */
#include "Keith.hpp"
#include "Main.hpp"
#include "Thread.hpp"
#include <iostream>
#include <cmath>

using std::cout;
using std::endl;


//--------------------------------------------------------------------------------------------------------------
// FindKeiths()
//
// Finds all Keith numbers from 1 to pLimit. We do nothing with the numbers we find.
//--------------------------------------------------------------------------------------------------------------

void FindKeiths
    (
    ulong pLimit
    )
{
	if (GetVerbose()) cout << "FindKeiths() Begin" << endl;
	for (ulong n = 0; n <= pLimit; n += 1) {
	        if (IsKeith(n))
	            ;
	    }
	if (GetVerbose()) cout << "FindKeiths() End" << endl;
}

//--------------------------------------------------------------------------------------------------------------
// FindKeithsThread()
//
// A thread which finds all keith numbers from 2 to pState->mLimit.
//--------------------------------------------------------------------------------------------------------------

void *FindKeithsThread
	(
	void *pState
	)
{
	// If running in verbose mode, then tell the user that the thread is beginning.
	    if (GetVerbose()) cout << "FindKeithsThread() Begin" << endl;

	    // We know that pState is really a pointer to a ThreadState structure, so type cast it.
	    ThreadState *state = static_cast<ThreadState *>(pState);

	    // Find all the keiths from 2 to state->mLimit.
	    FindKeiths(state->mLimit);

	    // The thread exit code is 0 (success).
	    state->mExitCode = 0;

	    // If running verbose mode, then tell the user that the thread is ending.
	    if (GetVerbose()) cout << "FindKeithsThread() End" << endl;

	    // Exit (terminate) the thread and return pState as the return variable.
	    pthread_exit(pState);
}


//--------------------------------------------------------------------------------------------------------------
// IsKeith()
//
// Returns true if pNum is a Keith.
//--------------------------------------------------------------------------------------------------------------
bool IsKeith
	(
	ulong pNum
	)
{
	//holds pNum
	int temp = pNum;
	//buffer holds the number of digits
	int buffer = ceil(log10(pNum));
	ulong sum = 0;
	int arr[buffer];

	for (int i = 0; i < buffer && temp != 0; i++) {
	    arr[i] = temp % 10;
	    sum += temp;
	    temp /= 10;
	  }

	while(sum < pNum)
	{
		for(int i = 0; i < buffer-1; i++) {
			arr[i] = arr[i+1];
		}
		arr[buffer-1] = arr[buffer-2] + arr[buffer-3];
	}

	if(pNum == sum)
		return true;
	else if(pNum >= sum)
		return false;

	return false;

}



